<!DOCTYPE html>






  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.2.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.2.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.2.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.2.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.2.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.2.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="一、IO流的分类 流向 输入流与 输出流    数据字节流：二进制（可以传输一切文件，包括纯文本，音频、视频等）字符流：文本文件，只能处理纯文本  功能 节点流：包裹源头 处理流：增强功能，提供性能   二、IO流基本步骤 创建源（文件/网络）  选择流  操作（读取/写出）  释放资源   三、流的种类1. 节点流###(１) 字节流 ####１) 输入流（InputStream / FileI">
<meta property="og:type" content="article">
<meta property="og:title" content="Bison分享日志">
<meta property="og:url" content="http://blog.bisondev.cn/2018/04/25/Java中的IO流/index.html">
<meta property="og:site_name" content="Bison分享日志">
<meta property="og:description" content="一、IO流的分类 流向 输入流与 输出流    数据字节流：二进制（可以传输一切文件，包括纯文本，音频、视频等）字符流：文本文件，只能处理纯文本  功能 节点流：包裹源头 处理流：增强功能，提供性能   二、IO流基本步骤 创建源（文件/网络）  选择流  操作（读取/写出）  释放资源   三、流的种类1. 节点流###(１) 字节流 ####１) 输入流（InputStream / FileI">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-10-21T04:15:08.286Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Bison分享日志">
<meta name="twitter:description" content="一、IO流的分类 流向 输入流与 输出流    数据字节流：二进制（可以传输一切文件，包括纯文本，音频、视频等）字符流：文本文件，只能处理纯文本  功能 节点流：包裹源头 处理流：增强功能，提供性能   二、IO流基本步骤 创建源（文件/网络）  选择流  操作（读取/写出）  释放资源   三、流的种类1. 节点流###(１) 字节流 ####１) 输入流（InputStream / FileI">






  <link rel="canonical" href="http://blog.bisondev.cn/2018/04/25/Java中的IO流/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title> | Bison分享日志</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Bison分享日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">I'm not perfect,but I keep trying</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-schedule">
    <a href="/schedule/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br />日程表</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">
    <a href="/sitemap.xml" rel="section">
      <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />站点地图</a>
  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.bisondev.cn/2018/04/25/Java中的IO流/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Bison Qin">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Bison分享日志">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-04-25 10:41:43" itemprop="dateCreated datePublished" datetime="2018-04-25T10:41:43+08:00">2018-04-25</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2017-10-21 12:15:08" itemprop="dateModified" datetime="2017-10-21T12:15:08+08:00">2017-10-21</time>
              
            
          </span>

          

          
            
          

          
          
             <span id="/2018/04/25/Java中的IO流/" class="leancloud_visitors" data-flag-title="">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="一、IO流的分类"><a href="#一、IO流的分类" class="headerlink" title="一、IO流的分类"></a>一、IO流的分类</h1><ol>
<li><p>流向<br> 输入流与 输出流  </p>
</li>
<li><p>数据<br>字节流：二进制（可以传输一切文件，包括纯文本，音频、视频等）<br>字符流：文本文件，只能处理纯文本</p>
</li>
<li><p>功能<br> 节点流：包裹源头<br> 处理流：增强功能，提供性能</p>
</li>
</ol>
<h1 id="二、IO流基本步骤"><a href="#二、IO流基本步骤" class="headerlink" title="二、IO流基本步骤"></a>二、IO流基本步骤</h1><ol>
<li><p>创建源（文件/网络）</p>
</li>
<li><p>选择流</p>
</li>
<li><p>操作（读取/写出）</p>
</li>
<li><p>释放资源</p>
</li>
</ol>
<h1 id="三、流的种类"><a href="#三、流的种类" class="headerlink" title="三、流的种类"></a>三、流的种类</h1><h2 id="1-节点流"><a href="#1-节点流" class="headerlink" title="1. 节点流"></a>1. 节点流</h2><p>###(１) 字节流</p>
<p>####１) 输入流（InputStream / FileInputStream / ByteArrayInputStream）<br>    A. 操作：read（字节数组）<br>            a) 中间容器<br>                byte[] flush = new byte[长度];</p>
<pre><code>        b) 接收长度
            int len = 0;

        c) 循环读取
            while( -1 != (len = 流.read(flush))){}

        d) 操作
            输出或者拷贝

B. 重点方法
        a) read(byte[] b)
        b) read(byte[] b, int offset, int len)
        c) close()
</code></pre><p>####２) 输出流（OutputStream / FileOutputStream / ByteArrayInputStream）<br>    A. 操作：write（字节数组， 0， 长度），输出</p>
<pre><code>B. 重点方法
        a) write(byte[] b)
        b) write(byte[] b, int off, int len)
        c) flush();
        d) close();
</code></pre><h3 id="２-字符流"><a href="#２-字符流" class="headerlink" title="(２) 字符流"></a>(２) 字符流</h3><p>####１) 输入流（Reader / FileReader）<br>    A. 操作<br>            //1、创建源<br>            File src =new File(“E:/xp/test/a.txt”);<br>            //2、选择流（FileReader）<br>            Reader reader =null;<br>            try {<br>                    reader =new FileReader(src);<br>                    //3、读取操作<br>                    char[] flush =new char[1024];<br>                    int len =0;<br>                    //循环读取<br>                    while(-1 != (len = reader.read(flush))){<br>                    //4、处理数据（字符数组转成 字符串）<br>                    String str =new String(flush,0,len);<br>                    System.out.println(str);<br>                  }<br>            } catch (FileNotFoundException e) {<br>                   e.printStackTrace();<br>                   System.out.println(“源文件不存在”);<br>            } catch (IOException e) {<br>                   e.printStackTrace();<br>                   System.out.println(“文件读取失败”);<br>            }finally{<br>                   try {<br>                           if (null != reader) {<br>                           //5、关闭流<br>                           reader.close();<br>                           }<br>                       } catch (Exception e2) {<br>                       }<br>            }</p>
<pre><code>B. 重点方法
        a) read(char[] cbuf )
        b) read(char[] cbuf, int off, int len)
        c) close()
</code></pre><p>####２) 输出流（Writer / FileWriter）<br>    A. 操作<br>            //1、创建源<br>            File dest = new File(“e:/xp/test/char.txt”);<br>            //2、选择流<br>            Writer wr = null;<br>            try {<br>                    //追加文件，而不是覆盖文件<br>                    wr = new FileWriter(dest);<br>                    //3、写出<br>                    String msg = “追加…..锄禾日当午\r\n码农真辛苦\r\n一本小破书\r\n一读一上午”;<br>                    wr.write(msg);<br>                    wr.append(“倒萨发了看电视剧 “);<br>                    wr.flush();<br>            } catch (FileNotFoundException e) {<br>                    e.printStackTrace();<br>            } catch (IOException e) {<br>                    e.printStackTrace();<br>            } finally {<br>                    try {<br>                            if (null != wr) {<br>                            //4、关闭流<br>                            wr.close();<br>                            }<br>                     } catch (Exception e2) {<br>                     }<br>            }</p>
<pre><code>B. 重点方法
        a) write(char[] cbuf)
        b) write(char[] cbuf, int off, int len)
        c) flush()
        d) close()
</code></pre><p>##2. 处理流<br>处理流：增强功能、提供性能，节点流之上</p>
<p>###(１) 缓冲流（BufferedInputStream / BufferedOutputStream ， BufferedReader / BufferedWrite）</p>
<p>####１) 字节缓冲流（BufferedInputStream / BufferedOutputStream）</p>
<p>####２) 字符缓冲流（BufferedReader / BufferedWriter）<br>        a. 重点方法<br>                a) readLine();<br>                b) newLine();</p>
<p>####３) 代码示例<br>        a. 字节流 + 缓冲流<br>                //1、建立联系 源(存在且为文件) +目的地(文件可以不存在)<br>                File src =new File(srcPath);<br>                File dest =new File(destPath);<br>                if(! src.isFile()){ //不是文件或者为null<br>                    System.out.println(“只能拷贝文件”);<br>                    throw new IOException(“只能拷贝文件”);<br>                }<br>                //2、选择流<br>                InputStream is = new BufferedInputStream(new FileInputStream(src));<br>                OutputStream os = new BufferedOutputStream( new FileOutputStream(dest));<br>                //3、文件拷贝   循环+读取+写出<br>                byte[] flush =new byte[1024];<br>                int len =0;<br>                //读取<br>                try {<br>                        while(-1!=(len=is.read(flush))){<br>                        //写出<br>                        os.write(flush, 0, len);<br>                    }<br>                 } catch (IOException e) {<br>                        e.printStackTrace();<br>                 }<br>                 os.flush(); //强制刷出<br>                 //4、关闭流<br>                 os.close();<br>                 try {<br>                         is.close();<br>                 } catch (IOException e) {<br>                         e.printStackTrace();<br>                 }</p>
<pre><code>b. 字符流 + 缓冲流
         //1、创建源 仅限于 字符的纯文本
         File src = new File(&quot;E:/xp/test/Demo03.java&quot;);
         File dest = new File(&quot;e:/xp/test/char.txt&quot;);
         //2、选择流
         BufferedReader reader = null;
         BufferedWriter wr = null;
         try {
                 reader = new BufferedReader(new FileReader(src));
                 wr = new BufferedWriter(new FileWriter(dest));
                 //3、读取操作
                 /*
                 char[] flush =new char[1024];
                 int len =0;
                 while(-1!=(len=reader.read(flush))){
                     wr.write(flush, 0, len);
                 }*/
                 //新增方法的操作
                 String line = null;
                 while(null != (line = reader.readLine())){
                     wr.write(line);
                     //wr.append(&quot;\r\n&quot;);
                     wr.newLine(); //换行符号
                 }
                 wr.flush();//强制刷出
         } catch (FileNotFoundException e) {
                 e.printStackTrace();
                 System.out.println(&quot;源文件不存在&quot;);
         } catch (IOException e) {
                 e.printStackTrace();
                 System.out.println(&quot;文件读取失败&quot;);
         }finally{
                 //4、关闭流
                 try {
                         if (null != wr) {
                         wr.close();
                     }
                } catch (Exception e2) {
                }
                try {
                        if (null != reader) {
                        reader.close();
                }
                } catch (Exception e2) {
                }
         }
</code></pre><p>###(２) 转换流（InputStreamReader / OutputStreamWriter）<br>功能：字节流转为字符流，处理乱码（编码集、解码集）<br>概念：</p>
<ul>
<li>编码：字符       —-编码字符集&gt;&gt;&gt;   二进制</li>
<li>解码：二进制   —-解码字符集&gt;&gt;&gt;  字符</li>
<li>乱码：编码和解码的字符集不统一，字节缺少，长度丢失</li>
</ul>
<p>编码与解码代码示例</p>
<pre><code>//指定解码字符集
BufferedReader br =new BufferedReader(
new InputStreamReader(                      //3).转换流
              new BufferedInputStream(            //2).缓冲流
              new FileInputStream(        //1).文件输入流
              new File(&quot;E:/xp/test/Demo03.java&quot;))),&quot;UTF-8&quot;)
            );
//写出文件 编码
BufferedWriter bw =new BufferedWriter(
              new OutputStreamWriter(
              new BufferedOutputStream(
              new FileOutputStream(new File(&quot;E:/xp/test/encode.java&quot;)))));

String info =null;
while(null!=(info=br.readLine())){
        //System.out.println(info);
        bw.write(info);
        bw.newLine();
}
//关闭流
bw.flush();
bw.close();
br.close();
</code></pre><p>###(３) 其他处理流</p>
<p>####１) 基本类型处理流</p>
<p>#####a. 从文件流中读取</p>
<p>######a) 输入流 DataInputStream  readXxx()<br>        //创建源<br>        File src =new File(destPath);<br>        //选择流<br>        DataInputStream dis =new DataInputStream(<br>                      new BufferedInputStream(<br>                      new FileInputStream(src)<br>                      )<br>        );</p>
<pre><code>//操作 读取的顺序与写出一致   必须存在才能读取
//不一致，数据存在问题
long num2 =dis.readLong();
double num1 =dis.readDouble();
String str =dis.readUTF();

dis.close();
System.out.println(num2+&quot;--&gt;&quot;+str);
</code></pre><p>######b) 输出流 DataOutputStream writeXxx()<br>        double point =2.5;<br>        long num=100L;<br>        String str =”数据类型”;</p>
<pre><code>//创建源
File dest =new File(destPath);
//选择流  DataOutputStream
DataOutputStream dos =new DataOutputStream(
                  new BufferedOutputStream(
                  new FileOutputStream(dest)
                  )
            );
//操作 写出的顺序 为读取准备
dos.writeDouble(point);
dos.writeLong(num);
dos.writeUTF(str);
dos.flush();

//释放资源
dos.close();
</code></pre><p>#####b. 从字节流中读取</p>
<p>######a) 输入流 DataInputStream<br>        //选择流<br>        DataInputStream dis =new DataInputStream(<br>                         new BufferedInputStream(<br>                         new ByteArrayInputStream(src)<br>                         )<br>                      );</p>
<pre><code>//操作 读取的顺序与写出一致   必须存在才能读取
double num1 =dis.readDouble();
long num2 =dis.readLong();
String str =dis.readUTF();

dis.close();

System.out.println(num1+&quot;--&gt;&quot;+num2+&quot;--&gt;&quot;+str);
</code></pre><p>######b) 输出流 DataOutputStream<br>        //目标数组<br>        byte[] dest =null;<br>        double point =2.5;<br>        long num=100L;<br>        String str =”数据类型”;</p>
<pre><code>//选择流 ByteArrayOutputStream  DataOutputStream
ByteArrayOutputStream bos =new ByteArrayOutputStream();
DataOutputStream dos =new DataOutputStream(
                   new BufferedOutputStream(
                   bos
                   )
               );
//操作 写出的顺序 为读取准备
dos.writeDouble(point);
dos.writeLong(num);
dos.writeUTF(str);      
dos.flush();
//释放资源
dos.close();
//转换成字节数组
dest = bos.toByteArray();
</code></pre><p>####２) 引用类型（对象）处理流<br>注意：</p>
<ul>
<li>先序列化后反序列化，反序列化顺序必须与序列化一致</li>
<li>不是说是有的对象都可以序列化，必须继承 java.io.Serializable才可以</li>
<li>不是所有的属性都需要序列化，用 transient 标注不需要序列化的变量</li>
</ul>
<p>序列化的实体类代码示例</p>
<pre><code>public class Employee implements java.io.Serializable {
        //不需要序列化
        private transient String name;
        private double salary;
        public Employee() {
        }
        public Employee(String name, double salary) {
            super();
            this.name = name;
            this.salary = salary;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public double getSalary() {
            return salary;
        }
        public void setSalary(double salary) {
            this.salary = salary;
        }
}
</code></pre><p>#####a. 输入流（反序列化）<br>    //创建源<br>    File src =new File(destPath);<br>    //选择流<br>    ObjectInputStream dis =new ObjectInputStream(<br>                        new BufferedInputStream(<br>                        new FileInputStream(src)<br>                        )<br>                  );</p>
<pre><code>//操作 读取的顺序与写出一致   必须存在才能读取
//不一致，数据存在问题
Object obj = dis.readObject();
if(obj instanceof Employee){
    Employee emp = (Employee)obj;
    System.out.println(emp.getName());
    System.out.println(emp.getSalary());
}

obj = dis.readObject();
int[] arr = (int[])obj;
System.out.println(Arrays.toString(arr));
dis.close();
</code></pre><p>#####b. 输出流（序列化）<br>    Employee emp = new Employee(“bjsxt”,1000000);<br>    int[] arr ={1,2,3,45};<br>    //创建源<br>    File dest = new File(destPath);<br>    //选择流  ObjectOutputStream<br>    ObjectOutputStream dos = new ObjectOutputStream(<br>                        new BufferedOutputStream(<br>                        new FileOutputStream(dest)<br>                        )<br>                   );<br>    //操作 写出的顺序 为读取准备<br>    dos.writeObject(emp);<br>    dos.writeObject(arr);<br>    //释放资源<br>    dos.close();</p>
<p>####３) 打印流</p>
<p>#####a. 输入流<br>    InputStream is = System.in;  //键盘输入<br>    //文件内容输入<br>    is = new BufferedInputStream(new FileInputStream(“e:/xp/test/print.txt”));<br>    Scanner sc = new Scanner(is);<br>    //System.out.println(“请输入:”);<br>    System.out.println(sc.nextLine());</p>
<p>#####b. 输出流</p>
<p>######a) 输出到文件<br>        System.out.println(“test”);<br>        PrintStream ps =System.out;<br>        ps.println(false);</p>
<pre><code>//输出到文件
File src = new File(&quot;e:/xp/test/print.txt&quot;);
ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(src)));
ps.println(&quot;io is so easy....&quot;);

ps.close();
</code></pre><p>######b) 切换输出流与控制台和文件流之间<br>        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(“e:/xp/test/print.txt”)),true));<br>        System.out.println(“a”);  //控制台  –&gt;文件<br>        System.out.println(“test”);<br>        //回控制台<br>        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true));<br>        System.out.println(“back….”);</p>
<h1 id="四、关闭流的工具类"><a href="#四、关闭流的工具类" class="headerlink" title="四、关闭流的工具类"></a>四、关闭流的工具类</h1><pre><code>public class FileUtil {

    /**
     * 工具类关闭流
     * 可变参数: ...  只能形参最后一个位置,处理方式与数组一致
     */
    public static void close(Closeable ... io){
        for(Closeable temp:io){
            try {
                if (null != temp) {
                    temp.close();
                }
            } catch (Exception e) {
            }
        }

    }

    /**
     * 使用泛型方法
     */
    public static &lt;T extends Closeable&gt; void closeAll(T ... io){
        for(Closeable temp:io){
            try {
                if (null != temp) {
                    temp.close();
                }
            } catch (Exception e) {
            }
        }
    }

}
</code></pre>
      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/12/05/JaveWeb环境配置/" rel="next" title="JaveWeb环境配置">
                <i class="fa fa-chevron-left"></i> JaveWeb环境配置
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Bison Qin</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">13</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">8</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一、IO流的分类"><span class="nav-number">1.</span> <span class="nav-text">一、IO流的分类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、IO流基本步骤"><span class="nav-number">2.</span> <span class="nav-text">二、IO流基本步骤</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三、流的种类"><span class="nav-number">3.</span> <span class="nav-text">三、流的种类</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-节点流"><span class="nav-number">3.1.</span> <span class="nav-text">1. 节点流</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#２-字符流"><span class="nav-number">3.1.1.</span> <span class="nav-text">(２) 字符流</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#四、关闭流的工具类"><span class="nav-number">4.</span> <span class="nav-text">四、关闭流的工具类</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Bison Qin</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a> v6.2.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.2.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.2.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.2.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.2.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.2.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.2.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.2.0"></script>



  



	





  





  










  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("M90nbI9KgVkqdeNl4kIE1aY4-gzGzoHsz", "3I8HRy0nT1nMlMw7enfvrnu5");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text(counter.get('time'));
            
            counter.save(null, {
              success: function(counter) {
                
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text('Counter not initialized! See more at console err msg.');
              console.error('ATTENTION! LeanCloud counter has security bug, see here how to solve it: https://github.com/theme-next/hexo-leancloud-counter-security. \n But you also can use LeanCloud without security, by set \'security\' option to \'false\'.');
            
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  
  

  

  

  

  

  

</body>
</html>
